#!/bin/sh

# dokcer中进行编译的脚本，在外部被srcrpm_build.sh调用
#获取系统架构
os_arch=$(arch)

#src.rpm的build的操作
rpm_build()
{
	#更换yum源
	sed -i 's/http/https/g' /etc/yum.repos.d/openEuler.repo
	sed -i 's/repo.openeuler.org/repo.huaweicloud.com\/openeuler/g' /etc/yum.repos.d/openEuler.repo
	yum makecache

	#搜索此目录下所以的src.rpm文件
	srcrpm_file=$(find $HOME -type f -name "*.src.rpm")
	#echo "$srcrpm_file"
	
	#SPECS目录,固定为用户目录下的rpmbuild
	spec_path=/root/rpmbuild/SPECS/
	
	#RPMS目录,固定为用户目录下的rpmbuild
	rpm_path=/root/rpmbuild/RPMS/${os_arch}/
	
	#判断rpmbuild工具是否安装,未安装则安装
	command -v rpmbuild >/dev/null 2>&1 
	if [ $? -ne 0 ];then
		echo "rpmbuild no install"
		yum install -y rpm-build rpmdev* 
		if [ $? -ne 0 ];then
			echo "install rpm-build rpmdev* failed !!!"
			exit 1
		fi
	fi
	
	cd /root/
	#获取src.rpm文件名
	file_name=${srcrpm_file##*/}
	echo -e "src rpm: ${file_name}\n"
	
	rpm -i $file_name
	#安装src.rpm失败,清空rpmbuild,继续处理
	if [ $? -ne 0 ];then
		echo -e "rpm -i $file_name failed !!!\n"
		exit 1
	fi

	#搜索spec文件
	cd $spec_path
	spec_file=$(find ./ -type f -name "*.spec")
	echo -e "SPEC: ${spec_file##*/}\n"
	
	if [ "$(cat $spec_file | grep "%global debug_package %{nil}")" = "" ];then
		sed -i '1i %global debug_package %{nil}' $spec_file
	fi


	#编译spec之前，安装编译的依赖
	#获取依赖列表
	#buildrequires=$(awk -F: '/^BuildRequires:/{print $0}' ${spec_file})
	buildrequires=$(cat ${spec_file} | grep -E "^BuildRequires:" |  awk -F ":" '{print $NF}')
	echo -e "software list needed in build: ${buildrequires}\n"

	#判断是否存在编译依赖
	if [ "$buildrequires" != "" ];then
		install_soft=$(echo $buildrequires | sed 's/,/ /g')
		install_soft=$(echo $install_soft | sed 's/>= [0-9].[0-9].[0-9]//g')
		install_soft=$(echo $install_soft | sed 's/>= [0-9].[0-9]//g')
		install_soft=$(echo $install_soft | sed 's/>=[0-9].[0-9]//g')

		echo -e "build $spec_file need software:${install_soft}\n"
		#安装编译依赖
		yum install -y $install_soft
		if [ $? -ne 0 ];then
			echo -e "yum install -y $install_soft failed !!!\n"
			exit 1	
		else
			echo -e "yum install -y $install_soft successed !!!\n"
		fi
	fi
	
	
	echo y | rpmbuild -ba $spec_file 
	#编译spec失败,清空rpmbuild,继续处理
	if [ $? -ne 0 ];then
		echo -e "rpmbuild -ba $spec_file --nodebuginfo failed !!!\n"
		exit 1	
	else
		echo -e "rpmbuild -ba $spec_file --nodebuginfo successed !!!\n"
		
	fi
	
	
	echo -e "\n\n"
}

rpm_build 
